import React, { useEffect } from 'react';
import {
  Form,
  Input,
  InputNumber,
  Select,
  DatePicker,
  Switch,
  Radio,
  Checkbox,
  Upload,
  Button,
  Row,
  Col,
  Divider,
  Space,
} from 'antd';
import { UploadOutlined, PlusOutlined } from '@ant-design/icons';
import DictionarySelect from '@/components/DictionarySelect';
import { useFieldOptions } from '@/hooks/useFieldOptions';
import type { FieldConfig, FormDTO, ValidationRule } from './types';
import type { FormInstance, Rule } from 'antd/es/form';
import dayjs from 'dayjs';

// 选项选择组件（用于 API 和静态选项）
interface SelectFieldOptionsProps {
  field: FieldConfig;
  formConfig: any;
  optionsConfig?: any;
  disabled?: boolean;
}

const SelectFieldOptions: React.FC<SelectFieldOptionsProps> = ({ 
  field, 
  formConfig, 
  optionsConfig,
  disabled 
}) => {
  const { options, loading } = useFieldOptions(optionsConfig);

  return (
    <Select
      placeholder={formConfig.placeholder || `请选择${field.label}`}
      disabled={disabled}
      allowClear
      showSearch
      loading={loading}
      filterOption={(input, option) =>
        String(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
      }
      options={options}
      {...formConfig.componentProps}
    />
  );
};

interface DynamicFormProps {
  fields: FieldConfig[];
  initialValues?: FormDTO;
  mode: 'create' | 'edit' | 'view';
  form?: FormInstance;
  onFinish?: (values: FormDTO) => void;
  loading?: boolean;
  layout?: 'horizontal' | 'vertical' | 'inline';
  labelCol?: { span: number };
  wrapperCol?: { span: number };
}

export const DynamicForm: React.FC<DynamicFormProps> = ({
  fields,
  initialValues = {},
  mode,
  form: externalForm,
  onFinish,
  loading = false,
  layout = 'horizontal',
  labelCol = { span: 6 },
  wrapperCol = { span: 18 },
}) => {
  const [internalForm] = Form.useForm();
  const form = externalForm || internalForm;

  // 格式化后的初始值
  const formattedInitialValues = React.useMemo(() => {
    if (!initialValues || !Array.isArray(fields)) return initialValues;
    
    const formattedValues = { ...initialValues };
    fields.forEach(field => {
      const value = formattedValues[field.key];
      
      // 处理日期字段
      if ((field.type === 'date' || field.type === 'datetime') && value) {
        // 如果已经是 dayjs 对象，直接使用
        if (dayjs.isDayjs(value)) {
          formattedValues[field.key] = value;
        } else {
          // 确保值是有效的日期
          const dayjsDate = dayjs(value);
          if (dayjsDate.isValid()) {
            formattedValues[field.key] = dayjsDate;
          } else {
            formattedValues[field.key] = undefined;
          }
        }
      }
      // 处理图片和文件字段 - 将URL字符串转换为fileList格式
      else if (field.type === 'image' || field.type === 'file') {
        // 如果是字符串URL，转换为fileList格式
        if (typeof value === 'string' && value) {
          formattedValues[field.key] = [
            {
              uid: '-1',
              name: value.split('/').pop() || 'image',
              status: 'done',
              url: value,
            }
          ];
        }
        // 如果已经是数组，确保每个元素都有必要的属性
        else if (Array.isArray(value)) {
          formattedValues[field.key] = value.map((item, index) => ({
            uid: item.uid || String(-(index + 1)),
            name: item.name || 'file',
            status: item.status || 'done',
            url: item.url || '',
            ...item,
          }));
        }
        // 其他情况设为空数组
        else {
          formattedValues[field.key] = [];
        }
      }
    });
    return formattedValues;
  }, [initialValues, fields]);

  // 设置初始值到表单
  useEffect(() => {
    if (formattedInitialValues) {
      form.setFieldsValue(formattedInitialValues);
    }
  }, [formattedInitialValues, form]);

  // 根据模式过滤字段
  const visibleFields = fields.filter(field => {
    const formConfig = { ...field.common, ...field.form };
    if (mode === 'create') {
      return formConfig.creatable !== false;
    } else if (mode === 'edit') {
      return formConfig.updatable !== false;
    }
    return true;
  });

  // 按分组组织字段
  const groupedFields: { [key: string]: FieldConfig[] } = {};
  visibleFields.forEach(field => {
    const group = field.form?.group || '基本信息';
    if (!groupedFields[group]) {
      groupedFields[group] = [];
    }
    groupedFields[group].push(field);
  });

  // 转换验证规则
  const convertRules = (rules?: ValidationRule[]): Rule[] => {
    if (!rules) return [];
    
    return rules.map(rule => {
      const antdRule: Rule = {};
      
      if (rule.required) {
        antdRule.required = true;
        antdRule.message = rule.message || '该字段为必填项';
      }
      
      if (rule.min !== undefined) {
        antdRule.min = rule.min;
        antdRule.message = rule.message || `最小值为 ${rule.min}`;
      }
      
      if (rule.max !== undefined) {
        antdRule.max = rule.max;
        antdRule.message = rule.message || `最大值为 ${rule.max}`;
      }
      
      if (rule.minLength !== undefined) {
        antdRule.min = rule.minLength;
        antdRule.message = rule.message || `最少 ${rule.minLength} 个字符`;
        antdRule.type = 'string';
      }
      
      if (rule.maxLength !== undefined) {
        antdRule.max = rule.maxLength;
        antdRule.message = rule.message || `最多 ${rule.maxLength} 个字符`;
        antdRule.type = 'string';
      }
      
      if (rule.pattern) {
        antdRule.pattern = rule.pattern;
        antdRule.message = rule.message || '格式不正确';
      }
      
      if (rule.validator) {
        antdRule.validator = async (_, value) => {
          const result = await rule.validator!(value);
          if (!result) {
            throw new Error(rule.message || '验证失败');
          }
        };
      }
      
      return antdRule;
    });
  };

  // 渲染表单字段
  const renderFormField = (field: FieldConfig) => {
    const formConfig = { ...field.common, ...field.form };
    const isView = mode === 'view';
    const disabled = isView || formConfig.disabled || (mode === 'edit' && !formConfig.editable);

    switch (field.type) {
      case 'text':
      case 'textarea':
        if (field.type === 'textarea') {
          return (
            <Input.TextArea
              placeholder={formConfig.placeholder || `请输入${field.label}`}
              disabled={disabled}
              rows={4}
              {...formConfig.componentProps}
            />
          );
        }
        
        // 如果有 addonAfter，使用 Space.Compact 包装
        if (formConfig.componentProps?.addonAfter) {
          const { addonAfter, ...restProps } = formConfig.componentProps;
          return (
            <Space.Compact style={{ width: '100%' }}>
              <Input
                placeholder={formConfig.placeholder || `请输入${field.label}`}
                disabled={disabled}
                {...restProps}
              />
              <Input disabled value={addonAfter} style={{ width: 'auto' }} />
            </Space.Compact>
          );
        }
        
        return (
          <Input
            placeholder={formConfig.placeholder || `请输入${field.label}`}
            disabled={disabled}
            {...formConfig.componentProps}
          />
        );

      case 'number':
        return (
          <InputNumber
            placeholder={formConfig.placeholder || `请输入${field.label}`}
            disabled={disabled}
            style={{ width: '100%' }}
            min={formConfig.rules?.find(r => r.min !== undefined)?.min}
            max={formConfig.rules?.find(r => r.max !== undefined)?.max}
            {...formConfig.componentProps}
          />
        );

      case 'select':
        // 获取选项配置
        const optionsConfig = formConfig.optionsConfig || 
          (formConfig.options ? { source: 'static' as const, options: formConfig.options } : undefined);
        
        // 如果使用字典
        if (optionsConfig?.source === 'dictionary' && optionsConfig.dictionaryCode) {
          return (
            <DictionarySelect
              code={optionsConfig.dictionaryCode}
              placeholder={formConfig.placeholder || `请选择${field.label}`}
              disabled={disabled}
              allowClear
              showSearch
              {...formConfig.componentProps}
            />
          );
        }
        
        // 如果使用 API 或静态选项
        return (
          <SelectFieldOptions
            field={field}
            formConfig={formConfig}
            optionsConfig={optionsConfig}
            disabled={disabled}
          />
        );

      case 'date':
      case 'datetime':
        return (
          <DatePicker
            style={{ width: '100%' }}
            placeholder={formConfig.placeholder || `请选择${field.label}`}
            disabled={disabled}
            showTime={field.type === 'datetime'}
            format={formConfig.dateFormat || (field.type === 'datetime' ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD')}
            {...formConfig.componentProps}
          />
        );

      case 'switch':
        return (
          <Switch
            disabled={disabled}
            checkedChildren="是"
            unCheckedChildren="否"
            {...formConfig.componentProps}
          />
        );

      case 'radio':
        return (
          <Radio.Group
            disabled={disabled}
            options={formConfig.options}
            {...formConfig.componentProps}
          />
        );

      case 'checkbox':
        return (
          <Checkbox.Group
            disabled={disabled}
            options={formConfig.options}
            {...formConfig.componentProps}
          />
        );

      case 'image':
        // Upload 组件不设置 fileList，由 Form.Item 通过 valuePropName="fileList" 控制
        return (
          <Upload
            name="image"
            listType="picture-card"
            maxCount={1}
            disabled={disabled}
            {...formConfig.componentProps}
          >
            {!disabled && (
              <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>上传图片</div>
              </div>
            )}
          </Upload>
        );

      case 'file':
        // Upload 组件不设置 fileList，由 Form.Item 通过 valuePropName="fileList" 控制
        return (
          <Upload
            name="file"
            disabled={disabled}
            {...formConfig.componentProps}
          >
            {!disabled && (
              <Button icon={<UploadOutlined />}>点击上传</Button>
            )}
          </Upload>
        );

      default:
        return (
          <Input
            placeholder={formConfig.placeholder || `请输入${field.label}`}
            disabled={disabled}
            {...formConfig.componentProps}
          />
        );
    }
  };

  // 处理表单提交
  const handleFinish = (values: any) => {
    // 格式化日期字段和图片字段
    const formattedValues = { ...values };
    if (Array.isArray(fields)) {
      fields.forEach(field => {
        // 格式化日期字段
        if ((field.type === 'date' || field.type === 'datetime') && formattedValues[field.key]) {
          // 检查是否是有效的 dayjs 对象
          if (dayjs.isDayjs(formattedValues[field.key]) && formattedValues[field.key].isValid()) {
            formattedValues[field.key] = formattedValues[field.key].format(
              field.form?.dateFormat || (field.type === 'datetime' ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD')
            );
          } else {
            formattedValues[field.key] = null;
          }
        }
        // 格式化图片和文件字段 - 将fileList转换回URL字符串
        if ((field.type === 'image' || field.type === 'file') && formattedValues[field.key]) {
          const fileList = formattedValues[field.key];
          // 确保 fileList 是数组
          if (Array.isArray(fileList) && fileList.length > 0) {
            const file = fileList[0];
            formattedValues[field.key] = file.url || file.response?.url || file.response?.data?.url || '';
          } else {
            // 如果不是数组或为空，设为空字符串
            formattedValues[field.key] = '';
          }
        }
      });
    }
    onFinish?.(formattedValues);
  };

  return (
    <Form
      form={form}
      layout={layout}
      labelCol={labelCol}
      wrapperCol={wrapperCol}
      onFinish={handleFinish}
      initialValues={formattedInitialValues}
    >
      {Object.entries(groupedFields).map(([groupName, groupFields], groupIndex) => (
        <div key={groupName}>
          {Object.keys(groupedFields).length > 1 && (
            <>
              <Divider orientation="left">{groupName}</Divider>
            </>
          )}
          <Row gutter={24}>
            {groupFields.map(field => {
              const formConfig = { ...field.common, ...field.form };
              const colSpan = formConfig.colSpan || 12;
              
              return (
                <Col key={field.key} span={colSpan}>
                  <Form.Item
                    label={field.label}
                    name={field.key}
                    rules={convertRules(formConfig.rules)}
                    tooltip={formConfig.tooltip}
                    valuePropName={
                      field.type === 'switch' 
                        ? 'checked' 
                        : (field.type === 'image' || field.type === 'file') 
                          ? 'fileList' 
                          : 'value'
                    }
                    getValueFromEvent={
                      (field.type === 'image' || field.type === 'file') 
                        ? (e) => {
                            // 如果已经是数组，直接返回
                            if (Array.isArray(e)) {
                              return e;
                            }
                            // 如果是事件对象，提取 fileList 并确保是数组
                            if (e && e.fileList) {
                              return Array.isArray(e.fileList) ? e.fileList : [];
                            }
                            // 如果是对象且有 file 属性
                            if (e && e.file) {
                              return [e.file];
                            }
                            // 其他情况返回空数组
                            return [];
                          }
                        : undefined
                    }
                    getValueProps={
                      (field.type === 'image' || field.type === 'file')
                        ? (value) => {
                            // 确保返回的值是数组格式的 fileList
                            let fileList = [];
                            
                            if (Array.isArray(value)) {
                              fileList = value;
                            } else if (typeof value === 'string' && value) {
                              // 字符串 URL 转换为 fileList
                              fileList = [{
                                uid: '-1',
                                name: value.split('/').pop() || 'file',
                                status: 'done',
                                url: value,
                              }];
                            } else if (value && typeof value === 'object') {
                              // 单个文件对象
                              fileList = [value];
                            }
                            
                            return { fileList };
                          }
                        : undefined
                    }
                  >
                    {renderFormField(field)}
                  </Form.Item>
                </Col>
              );
            })}
          </Row>
        </div>
      ))}
    </Form>
  );
};

export default DynamicForm;
